﻿using System;
using System.Collections.Generic;
using System.Text;

namespace TLang.Ast
{
    using Values;

    public class RecordDefNode : Node
    {
        private readonly NameNode _name;
        private readonly List<NameNode> _parents;
        private readonly Scope _propertyForm;


        public RecordDefNode(NameNode name, List<NameNode> parents, Scope propertyForm,
                         String file, int start, int end, int line, int col) : base(file, start, end, line, col)
        {
            this._name = name;
            this._parents = parents;
            this._propertyForm = propertyForm;
        }


        public override Value Interp(Scope s)
        {
            Scope properties = DeclareNode.EvalProperties(_propertyForm, s);

            if (_parents != null)
            {
                foreach (Node p in _parents)
                {
                    Value pv = p.Interp(s);
                    properties.PutAll(((RecordType)pv).Properties);
                }
            }
            Value r = new RecordType(_name.Id, this, properties);
            s.PutValue(_name.Id, r);
            return r;
        }

        public override String ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(Constants.ParenBegin);
            sb.Append(Constants.RecordKeyword).Append(" ");
            sb.Append(_name);

            if (_parents != null)
            {
                sb.Append(" (" + Node.PrintList(_parents) + ")");
            }

            foreach (String field in _propertyForm.KeysLocal)
            {
                sb.Append("[" + field);
                Map<String, Object> props = _propertyForm.LookupAllProps(field);
                foreach (var e in props)
                {
                    sb.Append(" :" + e.Key + " " + e.Value);
                }
                sb.Append("]");
            }

            sb.Append(Constants.ParenEnd);
            return sb.ToString();
        }
    }
}
